const mongoConnected = require("../lib/mongoose_connect");
const mongoModels = require("../lib/mongoose_schemas");
const lodash = require("lodash");
const fs = require("fs-extra");
const path = require("path");
const SAFEZONE_DATA = require("../test/210216_anquanqu-yulin.json");

mongoConnected.then(async $ => {
  // return
  let match_ids = (await mongoModels.Match.aggregate([{
    $match: {
      map_name: "Baltic_Main",//Desert_Main,DihorOtok_Main Savage_Main Baltic_Main
      is_customGame: false,
      is_eventMode: false,
      team_size: {
        $in: [1, 2, 4]
      }
    }
  }, {
    $project: {
      "match_id": "$match_id",
      "_id": 0
    }
  }])).map(e => e.match_id);
  let circles = [];
  for (let match_id of match_ids) {
    // debugger
    let gameStateEvents = (await mongoModels.Event.find({
      _T: "LogGameStatePeriodic",
      match_id: match_id
    })).map(e => e._doc).sort((a, b) => a._D.valueOf() - b._D.valueOf());
    let filtered = gameStateEvents.filter(e => {
      let isGame = e.common.isGame;
      let int = parseInt(isGame);
      return int && int === isGame;
    });
    let safetyZoneInfos = filtered.map(e => {
      return {
        safetyZoneRadius: e.gameState.safetyZoneRadius,
        safetyZonePosition: e.gameState.safetyZonePosition
      }
    });
    safetyZoneInfos = lodash.uniqWith(safetyZoneInfos, lodash.isEqual);
    circles = circles.concat(safetyZoneInfos)
    // debugger
  }
  let smallCircles = circles.filter(e => e.safetyZoneRadius <= 20000);
  // await fs.writeFile(path.join(__dirname, "../test/210216_anquanqu.json"), JSON.stringify({
  //   circles, smallCircles
  // }))
  debugger

  // return
  let GRID_LENGTH = 10200;
  let LENGTH = 816000 / GRID_LENGTH;
  let ARR = [];
  for (let i = 0; i < LENGTH; i++) {
    let a = (new Array(LENGTH)).fill(0);
    ARR[i] = a;
  }
  for (let i = 0; i < LENGTH; i++) {
    for (let j = 0; j < LENGTH; j++) {
      let pos = { x: i * GRID_LENGTH + GRID_LENGTH / 2, y: j * GRID_LENGTH + GRID_LENGTH / 2 };
      for (let zone of smallCircles) {
        let dis2dis = (pos.x - zone.safetyZonePosition.x) ** 2 + (pos.y - zone.safetyZonePosition.y) ** 2;
        let radius2 = zone.safetyZoneRadius ** 2;
        if (dis2dis < radius2) {
          ARR[i][j] += 1;
        }
        // debugger
      }
    }
  }
  await fs.writeFile(path.join(__dirname, "../test/210217_grids_in_safezonehaidao200m.json"), JSON.stringify({
    GRIDS_IN_SMALL: ARR,
    GRIDS_IN_NORMAL: ARR,
    GRID_LENGTH: GRID_LENGTH,
    max_in_small: lodash.max(lodash.flattenDeep(ARR)),
    max_in_normal: 100
  }))
  debugger






})